package view;

import java.awt.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import dao.*;
import modle.*;
import modle.Menu;
import util.*;

import java.awt.event.*;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class UpdateMenu extends JFrame {

	private JLabel updateLabel;
	private JLabel sibi_Label;
	private JLabel noi_Label;
	private JLabel ioi_Label;
	private JLabel poi_Label;
	private JLabel id_Label;
	private JLabel up_Label;
	private JButton btnSearch;
	private JButton btnFile;
	private JButton btnUpdate;
	private JPanel contentPane;
	private JTextField Name;
	private JTextField Id;
	private JTextField Price;
	private JTextField Description;
	private JTextField Picture;
	private JTextField Search;
	private String path="";
	private JComboBox comboBox;
	private List<Country> listCountries;
	private Locale locale;
	private JLabel backgroundlabel;
	private JLabel Img; 
	private JComboBox comboBoxMenu;
	ResourceBundle rd;
	MenuDao menuDao = new MenuDao();
	DbUtil dbUtil = new DbUtil();
	private JButton btnBack;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UpdateMenu frame = new UpdateMenu();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public UpdateMenu() {
		setTitle("Welcome to Food Corner");
		setIconImage(Toolkit.getDefaultToolkit().getImage(UpdateMenu.class.getResource("/img/iconImage.jpg")));
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 649, 614);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		updateLabel = new JLabel("Update old Item in Menu");
		updateLabel.setForeground(new Color(205, 133, 63));
		updateLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 23));
		updateLabel.setBounds(132, 13, 308, 52);
		contentPane.add(updateLabel);
		
		Name = new JTextField();
		Name.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Name.setColumns(10);
		Name.setBounds(246, 138, 224, 33);
		contentPane.add(Name);
		
		noi_Label = new JLabel("Name of Item: ");
		noi_Label.setForeground(new Color(70, 130, 180));
		noi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		noi_Label.setBounds(24, 137, 208, 33);
		contentPane.add(noi_Label);
		
		Id = new JTextField();
		Id.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Id.setColumns(10);
		Id.setBounds(246, 199, 224, 33);
		contentPane.add(Id);
		
		Price = new JTextField();
		Price.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Price.setColumns(10);
		Price.setBounds(246, 258, 224, 33);
		contentPane.add(Price);
		
		Description = new JTextField();
		Description.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Description.setColumns(10);
		Description.setBounds(246, 317, 224, 33);
		contentPane.add(Description);
		
		Picture = new JTextField();
		Picture.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Picture.setColumns(10);
		Picture.setBounds(246, 371, 224, 33);
		contentPane.add(Picture);
		
		poi_Label = new JLabel("Price of Item: ");
		poi_Label.setForeground(new Color(70, 130, 180));
		poi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		poi_Label.setBounds(24, 257, 208, 33);
		contentPane.add(poi_Label);
		
		id_Label = new JLabel("Item Description:");
		id_Label.setForeground(new Color(70, 130, 180));
		id_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		id_Label.setBounds(24, 316, 224, 33);
		contentPane.add(id_Label);
		
		up_Label = new JLabel("Upload Picture:");
		up_Label.setForeground(new Color(0, 0, 128));
		up_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		up_Label.setBounds(24, 370, 208, 33);
		contentPane.add(up_Label);
		
		ioi_Label = new JLabel("ID of Item: ");
		ioi_Label.setForeground(new Color(70, 130, 180));
		ioi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		ioi_Label.setBounds(24, 198, 208, 33);
		contentPane.add(ioi_Label);
		
		btnUpdate = new JButton("Update");
		btnUpdate.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 23));
		btnUpdate.setBounds(262, 461, 140, 38);
		contentPane.add(btnUpdate);
		btnUpdate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("正在向数据库中插入菜单信息");
				updateActionPerformed(e);
			}
		});
		
		Search = new JTextField();
		Search.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		Search.setBounds(246, 78, 224, 33);
		contentPane.add(Search);
		Search.setColumns(10);
		
		sibi_Label = new JLabel("Search Item by Id:");
		sibi_Label.setForeground(new Color(70, 130, 180));
		sibi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		sibi_Label.setBounds(24, 78, 208, 33);
		contentPane.add(sibi_Label);
		
		btnSearch = new JButton("Search");
		btnSearch.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 21));
		btnSearch.setBounds(490, 75, 114, 36);
		contentPane.add(btnSearch);
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("正在向数据库中查找菜单信息");
				searchActionPerformed(e);
			}
		});
		
		JLabel lblNewLabel_5 = new JLabel("");
		lblNewLabel_5.setIcon(new ImageIcon(UpdateMenu.class.getResource("/img/admin2.png")));
		lblNewLabel_5.setBounds(522, 124, 72, 101);
		contentPane.add(lblNewLabel_5);
		
		btnFile = new JButton("File");
		btnFile.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 17));
		btnFile.setBounds(470, 371, 89, 33);
		contentPane.add(btnFile);
		btnFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateimg();
			}
		});
		
		comboBox = new JComboBox<>();						//组合按钮或可编辑字段和下拉列表的组件
		comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		comboBox.addItemListener(new ItemListener() {		//用于接收项目事件的侦听器接口。
			public void itemStateChanged(ItemEvent e) {
				int index = comboBox.getSelectedIndex();	//返回列表中与给定项目匹配的第一个项目。 
					String arr[] = listCountries.get(index).getId().split("-");					//  ???（应该是遇见 - 就分割）
					locale = new Locale(arr[0], arr[1]);//	???   Locale对象代表具体的地理，政治或文化地区。（第一个是语言，第二个是国家）
					rd = ResourceBundle.getBundle("resources.content", locale);		//使用指定的基本名称，区域设置和类加载器获取资源包（这里好像没用类加载器）。 
					
					//rd到底有什么用
					
					try {
						changeLanguage();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
			}
		});
		comboBox.setBounds(490, 13, 98, 32);
		contentPane.add(comboBox);
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 19));
		btnBack.setBounds(14, 512, 89, 38);
		contentPane.add(btnBack);
		
		Img = new JLabel("");
		Img.setBounds(441, 433, 163, 122);
		contentPane.add(Img);
		
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Admin_Menu().setVisible(true);
				dispose();
			}
		});
		
		fillCountries();
		
//		comboBoxMenu = new JComboBox<>();
//		comboBoxMenu.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
//		comboBoxMenu.setBounds(34, 416, 131, 33);
//		contentPane.add(comboBoxMenu);
//		fillMenus();
		
	}
	
	private void fillMenus() {
		// TODO Auto-generated method stub
		for(int i=1;  ; ++i)
		{
			Connection con = null;
			try {
				con = dbUtil.getCon();
				Menu menu = menuDao.MenuSearch2(con, i);
				if(menu!=null) {
					comboBoxMenu.addItem(menu.getId() +"："+menu.getName());
				}
				else   break;
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}finally {
				try {
					// 关闭数据库连接
					dbUtil.closeCon(con);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	//查找图片的绝对路径
	protected void updateimg() {
		// TODO Auto-generated method stub
		
		JFileChooser file = new JFileChooser();
        file.setCurrentDirectory(new File(System.getProperty("user.home")));
        //filter the files
        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");	//什么意思，有什么用？？
        //创建具有 FileNameExtensionFilter的说明和文件扩展名的FileNameExtensionFilter。
        file.addChoosableFileFilter(filter);
        int result = file.showSaveDialog(null);
        //if the user click on save in Jfilechooser
        if(result == JFileChooser.APPROVE_OPTION){
            File selectedFile = file.getSelectedFile();
            path = selectedFile.getAbsolutePath();
            System.out.println(path);
            Picture.setText(path);
            Img.setIcon(ResizeImage(path, Img));
        }
         //if the user click on save in Jfilechooser
        else if(result == JFileChooser.CANCEL_OPTION){
            System.out.println("No File Select");
        }
	}

	private ImageIcon ResizeImage(String imgpath, JLabel label) {
		// TODO Auto-generated method stub
		ImageIcon img1 = new ImageIcon(imgpath);
		Image img2 = img1.getImage();
		Image img3 = img2.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
		ImageIcon img4 = new ImageIcon(img3);
		return img4;
	}

	//根据ID查找信息
	protected void searchActionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String id = Search.getText();
		if (StringUtil.isEmpty(id)) {
			JOptionPane.showMessageDialog(null, "ID不能为空");
			return;
		}
		
		System.out.println("正在查找该菜品的ID......");
		
		Connection con = null;
		try {
			con = dbUtil.getCon();
			Menu menu = menuDao.MenuSearch(con, id);
			if(menu!=null) {
				Name.setText(menu.getName());
				Id.setText(menu.getId());
				Price.setText(menu.getPrice());
				Description.setText(menu.getDescription());
				Picture.setText(menu.getPicture());
				Img.setIcon(ResizeImage(menu.getPicture(), Img));
			}
			else {
				JOptionPane.showMessageDialog(null, "数据库中没有此ID，查找失败");
			}
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}finally {
			try {
				// 关闭数据库连接
				dbUtil.closeCon(con);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	//更新菜单信息
	protected void updateActionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String name = Name.getText();
		String id = Id.getText();
		String price = Price.getText();
		String description = Description.getText();
		String picture = Picture.getText();
		
		if (util.StringUtil.isEmpty(name)) {
			JOptionPane.showMessageDialog(null, "name不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(id)) {
			JOptionPane.showMessageDialog(null, "id不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(price)) {
			JOptionPane.showMessageDialog(null, "price不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(description)) {
			JOptionPane.showMessageDialog(null, "description不能为空");
			return;
		}
		
		Menu menu = new Menu(name, id, price, description, picture);
		Connection con = null;
		
		try{
			con = dbUtil.getCon();
			int num = menuDao.MenuUpdate(con, menu, Search.getText());
			if(num>0) {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "菜品更改成功");
			}else {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "不存在该菜品");
			}
		}catch(Exception e1){
			JOptionPane.showMessageDialog(null, "出现异常，菜品更改失败！");
			e1.printStackTrace();
		}finally {
			try {
				// 关闭数据库连接
				dbUtil.closeCon(con);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	private void fillCountries() {
		// TODO Auto-generated method stub
		listCountries = new ArrayList<Country>();
		listCountries.add(new Country("en-US", "English"));
		listCountries.add(new Country("zh-CN", "中文"));
		
		for(Country c : listCountries)
			comboBox.addItem(c.getName());
	}

	protected void changeLanguage() {
		// TODO Auto-generated method stub
		
		updateLabel.setText(rd.getString("updateLabel"));
		sibi_Label.setText(rd.getString("sibi_Label"));
		noi_Label.setText(rd.getString("noi_Label"));
		ioi_Label.setText(rd.getString("ioi_Label"));
		poi_Label.setText(rd.getString("poi_Label"));
		id_Label.setText(rd.getString("id_Label"));
		up_Label.setText(rd.getString("up_Label"));
		btnSearch.setText(rd.getString("btnSearch"));
		btnFile.setText(rd.getString("btnFile"));
		btnUpdate.setText(rd.getString("btnUpdate"));
		btnBack.setText(rd.getString("btnBack"));
	}
}
